package com.thinkfit.jy.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;

import com.blankj.utilcode.util.AppUtils;
import com.common.lib.bean.ApplicationBean;
import com.common.lib.bean.VersionBean;
import com.common.lib.constant.EventBusEvent;
import com.common.lib.manager.DataManager;
import com.common.lib.network.OkHttpManager;
import com.thinkfit.jy.BuildConfig;
import com.thinkfit.jy.R;
import com.thinkfit.jy.contract.VersionContract;
import com.thinkfit.jy.presenter.VersionPresenter;
import com.thinkfit.jy.utils.EquipmentInfoUtils;
import com.thinkfit.jy.utils.SystemUtils;
import com.thinkfit.jy.utils.ThemeUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.HashMap;

/**
 * 软件更新
 */
public class VersionActivity extends MainActivity implements VersionContract.View {

    VersionBean versionBean;
    ProgressBar progressBar;
    RelativeLayout rootView;
    TextView tvUpdate;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_version;
    }

    public void init() {
        if (DataManager.Companion.getInstance().getMainStyle() == 3) {
            setBackground(R.id.rootView, R.drawable.app_bg_xm);
        }
        progressBar = findViewById(R.id.progressBar);
        tvUpdate = findViewById(R.id.tvUpdate);
        rootView = findViewById(R.id.rootView);

        resetDate();
        setText(R.id.tvVersion, "Ver " + BuildConfig.VERSION_NAME);
        ((VersionPresenter) getPresenter()).getVersion();
    }

    @Override
    public void onResume() {
        super.onResume();
        rootView.setBackgroundResource(ThemeUtils.getInstance().getMainTheme());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tvUpdate:
                if(versionBean != null){
                    if(EquipmentInfoUtils.getInstance().getVersionCode(getContext()) < versionBean.getNew_version()){
                        progressBar.setVisibility(View.VISIBLE);
                        tvUpdate.setVisibility(View.INVISIBLE);
                        ApplicationBean applicationBean = new ApplicationBean();
                        applicationBean.setDownload(versionBean.getApk_file_url());
//                        applicationBean.setDownload("http://fitlog-apk.oss-cn-hangzhou.aliyuncs.com/demo/app-release.apk");
                        applicationBean.setAppid(getContext().getPackageName());
                        OkHttpManager.Companion.getInstance().downloadApplication(applicationBean);
                    }
                }
                break;
        }
    }


    protected void showBottomUI() {
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceive(HashMap<String, Object> map) {
        if (map == null) {
            return;
        }
        if (map.containsKey(EventBusEvent.TIME_CHANGE)) {
            resetDate();
        } else {
            super.onReceive(map);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceive(ApplicationBean bean) {
        int progress = bean.getProgress();
        progressBar.setProgress(progress);
        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   "+bean.getDownloadFile()+"   progress : "+progress);
        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   DownloadStatus : "+bean.getDownloadStatus()+"   InstallStatus : "+bean.getInstallStatus());
        if (bean.getDownloadStatus() == 2 && bean.getInstallStatus() == 0) {  //下载完成了
            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa  111   DownloadStatus : "+bean.getDownloadStatus()+"   InstallStatus : "+bean.getInstallStatus());
            bean.setInstallStatus(1);
            installApk(bean.getDownloadFile());

        }
    }

    @NonNull
    @Override
    protected VersionContract.Presenter onCreatePresenter() {
        return new VersionPresenter(this);
    }

    @Override
    public void getVersionSuccess(VersionBean versionBean) {
        this.versionBean = versionBean;
        if(EquipmentInfoUtils.getInstance().getVersionCode(getContext()) < versionBean.getNew_version()){
            setText(R.id.tvMsg,getString(R.string.app_find_new_version));
            setViewsOnClickListener(R.id.tvUpdate);
        }

    }

    /**
     * 安装apk（非静默安装）
     * @param apkFile
     */
    private void installApk(File apkFile) {
        SystemUtils.getInstance().installApk(this, apkFile);
//        try {
//            Intent intent = new Intent(Intent.ACTION_VIEW);
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                Uri apkUri = FileProvider.getUriForFile(this, AppUtils.getAppPackageName() + ".fileprovider", apkFile);
//                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
//            } else {
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                Uri uri = Uri.fromFile(apkFile);
//                intent.setDataAndType(uri, "application/vnd.android.package-archive");
//            }
//            startActivity(intent);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }
}